//
//  TRTypeViewController.m
//  WeiMiLan
//
//  Created by anan on 15/3/4.
//  Copyright (c) 2015年 Mac. All rights reserved.
//

#import "TRTypeViewController.h"

@interface TRTypeViewController ()
{
    CGRect _rectViewContent;
    CGRect _rectViewPager;
    CGRect _rectViewPagerSC;
    CGRect _rectFragmentView;

}

@property (nonatomic,strong) TRTypePagerFragmentAdapter *adapter;

@end

@implementation TRTypeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     NSLog(@"TRTypeViewController");
    // Do any additional setup after loading the view from its nib.
    
    self.library = [[ALAssetsLibrary alloc] init];
    
    [QLPropertyUtils putStringByKey:@"BID" value:@""];
    
    self.viewGuide = [[[NSBundle mainBundle] loadNibNamed:@"QLGuideView" owner:self options:nil] lastObject];
    [self.view addSubview:self.viewGuide];
    if ([QLPropertyUtils getBoolByKey:@"guid_date" defaultValue:NO]==NO) {
        self.viewGuide.hidden = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(guideTap:)];
        [self.viewGuide addGestureRecognizer:tap];
    }
   // [self initNavigation];
    [self initChooseView];
    
    self.viewTabTtems.scrollsToTop = NO;
    
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
   
}

- (void)searchData:(NSMutableArray*)types
{
    if (types) {
        self.types = types;
        [self.viewPager removeFromSuperview];
        self.viewPager = nil;
        [self initViewPager];
    }else{
        [self loadTypes];
    }
}

- (void)guideTap:(id)sender
{
    self.viewGuide.hidden = YES;
    [QLPropertyUtils putBoolByKey:@"guid_date" value:YES];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [self initNavigation];
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view insertSubview:self.weChatNavigationBar belowSubview:self.viewGuide];
    self.weChatNavigationBar.titleLabel.text=@"";
    self.weChatNavigationBar.rightButton.left=230;
    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(shouLeftVC) forControlEvents:UIControlEventTouchUpInside];
    [self.weChatNavigationBar.leftButton setImage:nil forState:UIControlStateNormal];
    
    CGRect r = CGRectMake(9, 24, 36, 36);
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:r];
    NSDictionary *ui = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    if ([[ui ql_stringForKey:@"HEAD_PIC_URL"] isEqualToString:@"http://pingpic.vsmu.cn/upload/users"]) {
        //   NSString *str = ApplicationDelegate.urlHearder;
        NSString *str = [[NSUserDefaults standardUserDefaults]objectForKey:@"urlHeader"];
        
        [imageView sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"nodata_avator"]];
    } else {
        [imageView sd_setImageWithURL:[NSURL URLWithString:[ui ql_stringForKey:@"HEAD_PIC_URL"]] placeholderImage:[UIImage imageNamed:@"nodata_avator"]];
    }
    imageView.clipsToBounds = YES;
    imageView.layer.cornerRadius = 18;
    [self.weChatNavigationBar addSubview:imageView];
    
    [self.weChatNavigationBar.rightButton setImage:[UIImage imageNamed:@"seachBT"] forState:0];
    [self.weChatNavigationBar.rightButton addTarget:self action:@selector(search:) forControlEvents:UIControlEventTouchUpInside];
    self.weChatNavigationBar.rightButton.frame=CGRectMake(kUI_SCREEN_WIDTH-100, 30, 23, 23);
    
    [self.weChatNavigationBar.rightButton3 setImageEdgeInsets:UIEdgeInsetsMake(0, 1, 0, 1)];
    [self.weChatNavigationBar.rightButton3 setImage:[UIImage imageNamed:@"rli(1)"] forState:0];
    
    [self.weChatNavigationBar.rightButton3 addTarget:self action:@selector(pushDate) forControlEvents:UIControlEventTouchUpInside];
    [self.weChatNavigationBar.rightButton3 setImage:nil forState:1];
    self.weChatNavigationBar.rightButton3.hidden = NO;
    self.weChatNavigationBar.rightButton3.origin = CGPointMake(self.view.width - 32, self.weChatNavigationBar.rightButton.origin.y );
    self.weChatNavigationBar.rightButton3.width = 22;
    self.weChatNavigationBar.rightButton3.height = 22;
    
    [self loadTypes];
}

-(void)initChooseView
{
    
    self.chooseView=[[TRBar alloc] init];
    [self.chooseView.leftButton setTitle:@"取消" forState:0];
    self.chooseView.titleLabel.text=@"";
    
    UIButton * shoucangBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shoucangBtn.frame =CGRectMake(kUI_SCREEN_WIDTH-205, 32, 21, 23);
    shoucangBtn.center = CGPointMake(self.view.width/2.-35, shoucangBtn.center.y);
    [shoucangBtn setImage:[UIImage imageNamed:@"coll收藏按钮"] forState:UIControlStateNormal];
    [shoucangBtn setImage:[UIImage imageNamed:@"coll收藏按键按下"] forState:UIControlStateHighlighted];
    [self.chooseView addSubview:shoucangBtn];
    
    UIButton * downBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    downBtn.frame = CGRectMake(kUI_SCREEN_WIDTH-130, 32, 23, 25);
    downBtn.center = CGPointMake(self.view.width/2.+35, downBtn.center.y);
    [downBtn setImage:[UIImage imageNamed:@"down下载按钮"] forState:UIControlStateNormal];
    [downBtn setImage:[UIImage imageNamed:@"down下载按钮"] forState:UIControlStateHighlighted];
    [self.chooseView addSubview:downBtn];
    
    [downBtn addTarget:self action:@selector(downImageToAlbum:) forControlEvents:UIControlEventTouchUpInside];
    [shoucangBtn addTarget:self action:@selector(addCollection:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.chooseView.rightButton setTitle:@"全选" forState:0];
    self.chooseView.frame=self.weChatNavigationBar.bounds;
    [self.weChatNavigationBar addSubview:self.chooseView];
    
    self.chooseView.hidden = YES;
    [self.chooseView.leftButton addTarget:self action:@selector(cancelChooseView:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.chooseView.rightButton addTarget:self action:@selector(buttonSectionAllAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
}

- (void)pushDate
{
    TRNewsGoodsViewController *TVC=[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"TRNewsGoodsViewController"];
    [self.navigationController pushViewController:TVC animated:YES];
  //  [self presentViewController:TVC animated:YES completion:nil];
}

- (void)cancelChooseView:(id)sender
{
    self.chooseView.hidden = YES;
    TRTypeProductsListView *view = (TRTypeProductsListView*)self.viewPager.currentFragment.contentView;
    [view.alredaySelectArray removeAllObjects];
    [view.pullCollectionView reloadData];
}

- (void)buttonSectionAllAction:(id)sender
{
    TRTypeProductsListView *view = (TRTypeProductsListView*)self.viewPager.currentFragment.contentView;
    [view buttonSectionAllAction:sender];
}

- (void)downImageToAlbum:(id)sender
{
    TRTypeProductsListView *view = (TRTypeProductsListView*)self.viewPager.currentFragment.contentView;

    //复制过来的
    NSArray* allKeysArr = [view.alredaySelectArray allKeys];
    NSMutableArray * idArray = [@[] mutableCopy];
    for(NSString* key in allKeysArr)
    {
        if ([view.alredaySelectArray[key] boolValue]) {
            [idArray addObject:key];
        }
    }
    if (idArray.count==0) {
        
        MMProgressHUDShowError(@"请选择产品");
        return;
    }
    
    [MMProgressHUD showWithTitle:@"" status:@"相片保存中…" cancelBlock:^{}];
    
    NSLog(@"保存的图片%@",idArray);
    for(NSString* key in idArray) {
        [ApplicationDelegate.webAPI getWebAPIWithParams:@{TYPE:SERVICE_CODE_PRODUCT_DOWNLOAD,PRODUCT_TYPE_ID:key} andMethodNode:NODE_PRODUCT completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
            
            if (state==1) {
                NSString * title = responseObject[@"PRODUCT_RSP"][@"PRODUCT_INFO"][@"NAME"];
                dispatch_queue_t aQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                //创建1个queue group
                dispatch_group_t queueGroup = dispatch_group_create();
                
                __block int num = 1;
                for (int n=0;n<[responseObject[@"PRODUCT_RSP"][@"PRODUCT"] count];n++) {
                    
                    NSDictionary * albumDict = responseObject[@"PRODUCT_RSP"][@"PRODUCT"][n];
                    
                    NSURL *url = [NSURL URLWithString:albumDict[@"PIC_URL"]];
                    //获取concurrent queue
                    
                    dispatch_group_async(queueGroup, aQueue, ^{
                        NSData *resultData = [NSData dataWithContentsOfURL:url];
                        UIImage *img = [UIImage imageWithData:resultData];
                        //下面是保存的,保存不放在这里，放在接收数据的那边NAME
                        [self.library saveImage:img toAlbum:title withCompletionBlock:^(NSError *error) {
                            NSString * message = [NSString stringWithFormat:@"第%d个下载失败",n];
                            if (error!=nil) {
                                MMProgressHUDShowSuccess(message);
                                NSLog(@"Big error: %@", [error description]);
                                return;
                            }
                            message =[NSString stringWithFormat:@"第%d个下载成功",num++];
                            MMProgressHUDShowSuccess(message);
                        }];
                        dispatch_sync(dispatch_get_main_queue(), ^{
                            
                        });
                    });
                }
            }
        }];
    }
    [self cancelChooseView:nil];
}

- (void)addCollection:(id)sender
{
    TRTypeProductsListView *view = (TRTypeProductsListView*)self.viewPager.currentFragment.contentView;

    NSMutableArray * selectArray = [@[]mutableCopy];
    for (NSDictionary * idDict in view.currentArray) {
        if ([[view.alredaySelectArray objectForKey:[NSString stringWithFormat:@"%@",idDict[@"ID"]]] boolValue]) {
           [selectArray addObject:idDict[@"ID"]];
        }
    }
    
    if (selectArray.count==0) {
        
        MMProgressHUDShowError(@"请选择产品");
        return;
    }
    
    for (NSString * idString in selectArray) {
        [self updateDirectoryAddCollection:idString];
    }
    [self cancelChooseView:nil];
}

-(void)updateDirectoryAddCollection:(NSString *)idString
{
    
    [ApplicationDelegate.webAPI getWebAPIWithParams:@{@"type":[NSString stringWithFormat:@"%d",DirectoryAddCollection],PRODUCT_TYPE_ID:idString} andMethodNode:NODE_PRODUCT completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
        
        if (state==1) {
            NSLog(@"收藏：%@",responseObject);
            [SVProgressHUD showImage:nil status:@"收藏成功"];
        }
        
    }];
}

- (IBAction)buttonSortViewCloseAction:(id)sender
{
    self.viewSort.hidden = YES;
}

- (IBAction)buttonAction:(UIButton*)sender
{
    switch (sender.tag) {
        case 0:
        {
            TRNewsGoodsViewController *TVC=[[QLPlayerManager getStoryboard] instantiateViewControllerWithIdentifier:@"TRNewsGoodsViewController"];
            [self presentViewController:TVC animated:YES completion:nil];
        }
            break;
        case 1:
        {
            [QLPropertyUtils putStringByKey:@"SEX_CATEGORY" value:@"0"];
            TRTypeProductsListView *view = (TRTypeProductsListView*)self.viewPager.currentFragment.contentView;
            [view reload];
        }
            break;
        case 2:
        {
            [QLPropertyUtils putStringByKey:@"SEX_CATEGORY" value:@"1"];
            TRTypeProductsListView *view = (TRTypeProductsListView*)self.viewPager.currentFragment.contentView;
            [view reload];
        }
            break;
        case 3:
        {
            [QLPropertyUtils putStringByKey:@"SEX_CATEGORY" value:@"-1"];
            TRTypeProductsListView *view = (TRTypeProductsListView*)self.viewPager.currentFragment.contentView;
            [view reload];
        }
            break;
        default:
            break;
    }
    [self buttonSortViewCloseAction:nil];
}

- (void)loadTypes
{
    [QLMaskUtil showMaskLoadingWithView:self.view];
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    NSString *str = [NSString stringWithFormat:@"http://ping.vsmu.cn/app/Interface/Package?type=1018&userId=%@",ApplicationDelegate.currentUserId];
    [requestManager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        if (responseObject) {
            self.types = responseObject[@"PACKAGE_RSP"][@"PACKAGE"];
            if (self.viewPager==nil) {
                [self initViewPager];
            }
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        
    }];
}

- (void)initViewPager
{
    CGRect rect = CGRectMake(0, 0, self.viewContent.frame.size.width, self.viewContent.frame.size.height);
    self.viewPager = [[QLViewPager alloc]initWithFrame:rect];
  //  self.viewPager.pageIndicatorHeight = 30;
    self.viewPager.backgroundColor = [UIColor whiteColor];//[UIColor colorWithWhite:0.092 alpha:1.000];
    self.viewPager.scrollView.backgroundColor = [UIColor clearColor];
    self.viewPager.showPageIndicator = NO;
    [self.viewPager setup];
    [self.viewContent addSubview:self.viewPager];
    self.adapter = [[TRTypePagerFragmentAdapter alloc] initWithViewController:self];
    self.adapter.types = self.types;
    [self updateTabitems];
    [self.viewPager setAdapter:self.adapter];
    
    self.viewPager.delegate = self;
    [self onPageChange:self.viewPager select:self.viewPager.currentIndex];
}

- (void)updateTabitems
{
    if (self.buttons) {
        for (UIView *view in self.buttons) {
            [view removeFromSuperview];
        }
        [self.buttons removeAllObjects];
    }
    if (self.buttons==nil) {
        self.buttons = [NSMutableArray new];
    }
    
    int x = 5;
    int i = 0;
    for (NSDictionary *dic in self.types) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:[dic ql_stringForKey:@"NAME"] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.viewTabTtems addSubview:button];
        [button sizeToFit];
        CGRect r = button.frame;
        r.origin.x = x;
        r.size.width = r.size.width+10;
        r.size.height = self.viewTabTtems.frame.size.height;
        button.frame = r;
        button.tag = i;
        [button addTarget:self action:@selector(buttonTabAction:) forControlEvents:UIControlEventTouchUpInside];
        x = r.origin.x+r.size.width+10;
        i++;
        [self.buttons addObject:button];
    }
    self.viewTabTtems.contentSize = CGSizeMake(x, self.viewTabTtems.frame.size.height);
}

- (void)buttonTabAction:(UIButton*)sender
{
    self.viewPager.currentIndex = (int)sender.tag;
    [self buttonCloseAllTypeView:nil];
}

-(void)shouLeftVC
{
    [ApplicationDelegate.ddVC showLeftController:YES];
}

-(void)search:(id)btn{
    TRSearchProductViewController *vc = [[TRSearchProductViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)removeTopButton{
    
}

- (void)buttonCloseAllTypeView:(id)sender
{
    self.typeAllView.hidden = YES;
}

- (IBAction)buttonAllTypeAction:(id)sender
{
    if (self.buttonsAll) {
        for (UIView *view in self.buttonsAll) {
            [view removeFromSuperview];
        }
        [self.buttonsAll removeAllObjects];
    }
    if (self.buttonsAll==nil) {
        self.buttonsAll = [NSMutableArray new];
    }
    
    if (self.typeAllView==nil) {
        self.typeAllView = [[[NSBundle mainBundle] loadNibNamed:@"TRTypeAllView" owner:self options:nil] lastObject];
        CGRect r = CGRectMake(0, 64, QL_WIDTH, 44);
        self.typeAllView.frame = r;
        [self.view addSubview:self.typeAllView];
        [self.typeAllView.buttonClose addTarget:self action:@selector(buttonCloseAllTypeView:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    self.typeAllView.hidden = NO;
    
    int x = 5;
    int rows = 0;
    int i = 0;
    for (NSDictionary *dic in self.types) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:[dic ql_stringForKey:@"NAME"] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [self.typeAllView addSubview:button];
        [button sizeToFit];
        CGRect r = button.frame;
        r.origin.x = x;
        r.origin.y = (36+5)*rows+36;
        r.size.width = 70;
        r.size.height = 36;
        button.frame = r;
        button.tag = i;
        [button addTarget:self action:@selector(buttonTabAction:) forControlEvents:UIControlEventTouchUpInside];
        x = r.origin.x+r.size.width+10;
        
        if ((i+1)%4==0) {
            rows++;
            x = 5;
        }
        [self.buttonsAll addObject:button];
        
        if (i==self.viewPager.currentIndex) {
            [button setTitleColor:[UIColor colorWithRed:0.735 green:0.507 blue:0.000 alpha:1.000] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:18];
        }
        
        i++;
    }
    
    CGRect r = CGRectMake(0, 64, QL_WIDTH, (36+5)*(rows+1)+36+5);
    self.typeAllView.frame = r;
}

#pragma mark --QLViewPagerDelegate
- (void)onPageChange:(QLViewPager *)viewPager select:(int)select
{
    if (self.buttons.count == 0) {
        return;
    }
    
    //   [self.selectedButton setBackgroundImage:nil forState:UIControlStateNormal];
    for (UIButton *button in self.buttons) {
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:12];
    }
    //
    [self.selectedButton setBackgroundImage:nil forState:UIControlStateNormal];
    self.selectedButton = nil;
    UIButton *button = [self.buttons objectAtIndex:select];
    self.selectedButton = button;
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];//[UIColor colorWithRed:0.735 green:0.507 blue:0.000 alpha:1.000] forState:UIControlStateNormal];
    // if (button.isSelected) {
    [self.selectedButton setBackgroundImage:[UIImage imageNamed:@"button_line"] forState:UIControlStateNormal];
    // } else {
    //    [button setBackgroundImage:nil forState:UIControlStateNormal];
    //  }
    
    button.titleLabel.font = [UIFont systemFontOfSize:14];
}

- (void)fullScreen
{
    if (CGRectIsEmpty(_rectViewContent)) {
        _rectViewContent = self.viewContent.frame;
        _rectViewPager = self.viewPager.frame;
        _rectViewPagerSC = self.viewPager.scrollView.frame;
    }
    
    CGRect r = CGRectMake(0, 0, _rectViewContent.size.width, _rectViewContent.size.height+44+32+15);
    self.viewContent.frame = r;
    self.weChatNavigationBar.hidden = YES;
    self.viewPager.frame = CGRectMake(0, 0, r.size.width,r.size.height);
    self.viewPager.scrollView.frame = self.viewPager.frame;
    self.viewPager.tabPageIndicator.hidden = YES;
    self.viewPager.scrollView.scrollEnabled = NO;
    
    self.viewSort.hidden = YES;
    self.viewContentTab.hidden = YES;
}

- (void)fullScreenExit
{
    if (CGRectIsEmpty(_rectViewContent)) {
        _rectViewContent = self.viewContent.frame;
        _rectViewPager = self.viewPager.frame;
        _rectViewPagerSC = self.viewPager.scrollView.frame;
    }
    
    CGRect r = _rectViewContent;
    self.viewContent.frame = r;
    self.weChatNavigationBar.hidden = NO;
    self.viewPager.frame = _rectViewPager;
    self.viewPager.scrollView.frame = _rectViewPagerSC;
    self.viewPager.tabPageIndicator.hidden = NO;
    self.viewPager.scrollView.scrollEnabled = YES;
    TRTypeProductsListView *view = (TRTypeProductsListView*)self.viewPager.currentFragment.contentView;
    if (CGRectIsEmpty(_rectFragmentView)) {
        _rectFragmentView = view.frame;
    }
    r = view.frame;
    r.size.height = _rectFragmentView.size.height;
    view.frame = r;
    
    self.viewContentTab.hidden = NO;
}

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:YES];
//    self.view.backgroundColor = [UIColor whiteColor];
//}

@end
